<template>
	<a-dropdown class="app-control-tree__node__title" :trigger="['contextmenu']">
		<span
			:class="['app-tree-node__text', cssName]"
			:title="tooltip ? tooltip : text"
			v-badge="count"
		>
			<template v-if="editState">
				<a-input
					allowClear
					type="text"
					v-model:value="editValue"
					@pressEnter="closeEdit"
					@blur="closeEdit"
					class="app-tree-node__text__input"
				/>
			</template>
			<template v-else>
				<template v-if="textCustomCode && textScriptCode">
					<span
						@dblclick="openEdit(getCustomText(textScriptCode!))"
						:domPropsInnerHtml="getCustomText(textScriptCode)"
					></span>
				</template>
				<template v-else-if="html">
					<span @dblclick="openEdit(html!)" :domPropsInnerHtml="html"></span>
				</template>
				<template v-else>
					<span @dblclick="openEdit(text)">{{ text }}</span>
				</template>
			</template>
		</span>
		<template v-if="contextMenus" #overlay>
			<AppContextMenu
				:items="contextMenus"
				@item-click="(item: IParam, event: MouseEvent) => { handleContextMenuItemClick(item, event) }"
			></AppContextMenu>
		</template>
	</a-dropdown>
</template>

<script setup lang="ts">
import { treeNodeTitleProps } from '../tree';
import { AppContextMenu } from '@/components/widgets/context-menu';
import { IParam } from '@/core';
const props = defineProps(treeNodeTitleProps);
const emit = defineEmits<{
	(name: 'value-change', value: string): void;
	(name: 'context-menu-item-click', value: any): void;
}>();
const editState = ref(false);
const editValue = ref('');

const getCustomText = (scriptCode: string): string => {
	let text = '';
	const code = scriptCode.replace(new RegExp('return', 'g'), `icon =`);
	eval(code);
	return text;
};

const openEdit = (text: string) => {
	if (props.allowEditText) {
		editValue.value = text;
		editState.value = true;
	}
};

const closeEdit = ($event: any) => {
	editState.value = false;
	emit('value-change', editValue.value);
};

const handleContextMenuItemClick = (item: IParam, event: MouseEvent) => {
	emit('context-menu-item-click', { item, event });
};
</script>
